package org.wltea.analyzer.dic;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;


/**
 * 定时执行后,根据时间获取最新的词
 * <p>
 * Created by 张栋 on 2017/6/13 10:38
 */
public class Monitor implements Runnable {
    private static CloseableHttpClient httpclient = HttpClients.createDefault();
    private static final SimpleDateFormat sdfGMT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    static {
        sdfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private String last_modified;
    private String location;

    public static void main(String[] args) {
        Monitor monitor = new Monitor("http://localhost:8092/dic/extdic.do");
        new Thread(monitor).start();
    }

    public String getLast_modified() {
        return last_modified;
    }

    public void setLast_modified(String last_modified) {
        this.last_modified = last_modified;
    }

    public Monitor(String location) {
        this.location = location;
        this.last_modified = null;
    }


    //出错时,循环取请求地址
    private int currentIndex =0;
    private int maxIndex=0;
    private String[] urls =null;
    private String[] last_modified_array=null;
    private boolean isfrist=true;
    private  void initUrl(){
        if(isfrist){
            if(location.indexOf(";")!=-1){
                urls = location.split(";");
                maxIndex=urls.length;
                this.location=urls[currentIndex];
                last_modified_array = new String[maxIndex];
            }
            isfrist=false;
        }
    }

    private void changeUrl(){
        if(maxIndex!=0){
            //先保存当前最后更新时间
            last_modified_array[currentIndex]=this.last_modified;

            //切换到下一个位置
            currentIndex=(++currentIndex)%maxIndex;

            //取新的地址与时间
            this.location=urls[currentIndex];
            this.last_modified=last_modified_array[currentIndex];
            System.out.println("切换url至 : "+this.location);
        }
    }


    @Override
    public void run() {
        initUrl();
        System.out.println("start remote testing …… ");
        RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(15000).build();
        HttpGet head = new HttpGet(this.location);
        head.setConfig(rc);

        if (this.last_modified != null) {
            try {
                head.setHeader("If-Modified-Since", sdfGMT.format(sdf.parse(this.last_modified)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(head);

            if (response.getStatusLine().getStatusCode() == 200) {

                String timestr = null;
                try {
                    timestr = response.getLastHeader("Last-Modified").getValue();
                } catch (Exception e) {
                    System.out.printf("准备 重新加载词库");
                    //获取最后更新时间如果为 空出错时,代表需要重新加载词库
                    this.last_modified = null;
                    Dictionary.getSingleton().reLoadMainDict();
                    return ;
                }

                //
                timestr = sdf.format(sdfGMT.parse(timestr));
                if ((!timestr.equalsIgnoreCase(this.last_modified))) {

                    /**
                     * Created by 张栋 on 2017/6/13 10:37
                     */
                    List<String> ableWorld = new ArrayList();
                    List<String> disableWorld = new ArrayList();

                    String charset = "UTF-8";
                    System.out.println(response.getEntity());
                    if (response.getEntity().getContentType().getValue().contains("charset=")) {
                        String contentType = response.getEntity().getContentType().getValue();
                        charset = contentType.substring(contentType.lastIndexOf("=") + 1);
                    }
                    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
                    String line;
                    while ((line = in.readLine()) != null) {
                        if (line.startsWith("!")) {
                            disableWorld.add(line);
                        } else {
                            ableWorld.add(line);
                        }
                    }
                    in.close();
                    response.close();
                    Dictionary singleton = Dictionary.getSingleton();
                    singleton.addWords(ableWorld);
                    singleton.disableWords(disableWorld);


                    System.out.println("remote_ext_dic return success: lastModifiedTime change " + this.last_modified + " to " + timestr);
                    this.last_modified = timestr;
                }
            } else if (response.getStatusLine().getStatusCode() == 304) {
                System.out.println("remote_ext_dic "+this.location+" return 304  lastModifiedTime " +this.last_modified);
                changeUrl();
            } else {
                System.err.println("remote_ext_dict " + this.location + " return bad code " + response.getStatusLine().getStatusCode() + " lastModifiedTime "+this.last_modified);
                changeUrl();
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.err.println("remote_ext_dict  error!" + e.getMessage());
            changeUrl();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
